package com.cherry.androidviewdemo.widget

import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import kotlin.math.max

/**
 * 定义一个垂直排列的ViewGroup
 * @author DongMS
 * @since 2020/5/20
 */
class MyLinLayout : ViewGroup {
    constructor (context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    //widthMeasureSpec和heightMeasureSpec是父类传递过来给当前view的一个建议值
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)

        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)

        var height = 0
        var width = 0

        for (i in 0 until childCount) {
            val childView = getChildAt(i)
            measureChild(childView, widthMeasureSpec, heightMeasureSpec)

            val marginLayoutParams = childView.layoutParams as MarginLayoutParams

            //高度叠加
            val childHeight = childView.measuredHeight + marginLayoutParams.topMargin + marginLayoutParams.bottomMargin
            height += childHeight
            val childWidth = childView.measuredWidth + marginLayoutParams.leftMargin + marginLayoutParams.rightMargin

            //宽度最大值
            width = max(childWidth, width)
        }
        //当模式是MeasureSpec.EXACTLY时，我们就不必要设定我们计算的大小了，因为这个大小是用户指定的，我们不应更改。
        // 但当模式是MeasureSpec.AT_MOST时，也就是说用户将布局设置成了wrap_content，我们就需要将大小设定为我们计算的数值，因为用户根本没有设置具体值是多少，需要我们自己计算。
        setMeasuredDimension(if (widthMode == MeasureSpec.EXACTLY) widthSize else width, if (heightMode == MeasureSpec.EXACTLY) heightSize else height)
    }


    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        //layout子控件
        var top = 0
        for (i in 0 until childCount) {
            val childView = getChildAt(i)

            val lp = childView.layoutParams as MarginLayoutParams
            val left = lp.leftMargin + lp.rightMargin
            val childWidth = childView.measuredWidth

            top += lp.topMargin + lp.bottomMargin
            val childHeight = childView.measuredHeight

            childView.layout(left, top, left + childWidth, top + childHeight)
            top += childHeight
        }
    }

    //margin配置

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
        return MarginLayoutParams(context, attrs)
    }

    override fun generateLayoutParams(p: LayoutParams?): LayoutParams {
        return MarginLayoutParams(p)
    }

    override fun generateDefaultLayoutParams(): LayoutParams {
        return MarginLayoutParams(MarginLayoutParams.MATCH_PARENT, MarginLayoutParams.MATCH_PARENT)
    }

}